/*jslint sloppy: true */
/*global require */
var LM = require('../global');
var angular = require('angular');
require('./detail.html');

LM.controller('Task', function ($scope, Task, $routeParams, $location, $q,
								Project, Token, Result) {
	var task, projectId = $routeParams.projectId,
		taskId = $routeParams.taskId;

	function getResultList() {
		$scope.resultList = Result.query({
			projectId: projectId,
			task: taskId,
			mask: 'data,updatetime,comment'
		});
	}

	task = $scope.task = Task.get({ taskId: taskId, projectId: projectId }, function () {
		$scope.taskComment = task.comment;
		task.schemas = angular.fromJson(task.schemas);
		getResultList();
	});

	$scope.resultSelection = [];
	$scope.deleteResult = function () {
		var deleteReqs = [];
		angular.forEach($scope.resultSelection, function (sel, index) {
			if (sel === true) {
				deleteReqs.push($scope.resultList[index].$remove().$promise);
			}
		});
		$q.all(deleteReqs).then(function () {
			getResultList();
			$scope.resultSelection.length = 0;
		});
	};

	$scope.updateTask = function () {
		task.comment = $scope.taskComment;
		task.$modify();
	};
	$scope.removeTask = function () {
		$scope.task.$remove(null, function () {
			$location.url('/project/' + projectId + '/task');
		});
	};
	$scope.removeTaskEnter = function () {
		if ($scope.deleteWord === 'DELETE') {
			$scope.removeTask();
		}
	};
	$scope.removeReportEnter = function () {
		if ($scope.deleteReportWord === 'DELETE') {
			$scope.deleteResult();
		}
		$scope.isRemoveReport = false;
	};
	$scope.setNotDraft = function () {
		task.draft = false;
		$scope.updateTask();
	};

	// init
	$scope.project = Project.get({ projectId: projectId });
	$scope.token = Token.get({ projectId: projectId });
	$scope.$watchGroup([
		'project.probePath',
		'token.token'
	], function () {
		$scope.runnerUrl = $scope.project.getUrl(true, $scope.token.token, { id: taskId });
	});

	$scope.queryConfig.clear().setActive();
	$scope.navConfig.setHref('#/project/' + projectId + '/task').setType('back');
});
